# -*- coding: utf-8 -*-
# !/usr/bin/env python
import uuid

from rest_framework.views import APIView
from components.models import SoftManagement, ConfManagement
from components.resource_management.soft_manage.dao import query_soft_info, post_install_conf, get_install_conf, \
    update_install_conf
from utils.views import Result

class SoftManage(APIView):
    def get(self, request):
        data = request.query_params
        soft_info = {}
        if data['soft_id']:
            soft_info['form_soft'] = query_soft_info(data['soft_id'])
        if soft_info['form_soft']['conf_manage_ids']:
            soft_info['install_conf'] = get_install_conf(soft_info['form_soft']['conf_manage_ids'])

        return Result.success_response(data=soft_info, msg='查询成功')

    def post(self, request):
        data = request.data
        form_soft = data['form_soft']
        form_soft['status'] = 1
        form_soft['conf_manage_ids'] = str(uuid.uuid1())
        try:
            post_install_conf(data['install_conf'], form_soft['conf_manage_ids'])
            save_data = SoftManagement(**form_soft)
            save_data.save()
        except Exception as e:
            return Result.fail_response(msg=str(e))

        return Result.success_response(msg='保存成功')


    def put(self, request):
        data_dict = request.data.copy()

        form_soft = data_dict['form_soft']

        SoftManagement.objects.filter(soft_id=form_soft['soft_id']).update(
            package_id=form_soft['package_id'],
            host_id=form_soft['host_id'],
            soft_nick=form_soft['soft_nick'],
            soft_code=form_soft['soft_code'],
            soft_install_on=form_soft['soft_install_on'],
            soft_install_code=form_soft['soft_install_code'],
            package_repository_code=form_soft['package_repository_code'],
            soft_install_url=form_soft['soft_install_url'],
            soft_install_cmd=form_soft['soft_install_cmd'],
            soft_start_cmd=form_soft['soft_start_cmd'],
            soft_restart_cmd=form_soft['soft_restart_cmd'],
            soft_stop_cmd=form_soft['soft_stop_cmd'],
            soft_check_code=form_soft['soft_check_code'],
            soft_check_url=form_soft['soft_check_url'],
            comment=form_soft['comment'],
            soft_subsumption_code=form_soft['soft_subsumption_code']
        )

        update_install_conf(data_dict['install_conf'])

        return Result.success_response(msg='修改成功')


    def delete(self, request):
        data = request.data
        soft_ids = data['soft_ids']

        SoftManagement.objects.filter(soft_id__in=soft_ids).update(status=0)

        return Result.success_response(msg='删除成功')